import time
import logging
from selenium.webdriver.common.by import By
import json
from urllib.parse import urlparse
import random
from selenium.common.exceptions import WebDriverException


def get_boss_list(driver):
    captured_urls = []
    # 等待 1 到 5 秒的随机时间，精确到毫秒
    random_sleep_time = random.uniform(1, 5)
    logging.info(f"等待 {random_sleep_time:.3f} 秒...")
    time.sleep(random_sleep_time)

    # 清空浏览器日志缓冲区
    driver.get_log("performance")

    # 点击按钮
    refresh_btn = driver.find_element(By.XPATH, '//*[@id="wrap"]/div[1]/div[1]/dl[1]/dt/a')
    refresh_btn.click()

    # 等待页面加载
    time.sleep(random_sleep_time)
    logging.info("切换到职位管理页面")

    # 每次页面加载后，启用 Network 并设置缓冲区
    driver.execute_cdp_cmd("Network.enable", {
        "maxTotalBufferSize": 10000000,
        "maxResourceBufferSize": 5000000
    })

    # 等待一段时间，确保页面加载并发起请求
    time.sleep(random_sleep_time)

    # 获取浏览器的性能日志
    logs = driver.get_log("performance")

    # 遍历日志，捕获相关网络请求和响应
    for item in logs:
        log = json.loads(item["message"])["message"]

        if log["method"] == 'Network.responseReceived':
            # 获取响应的URL
            urls = log['params']['response']['url']
            captured_urls.append(urls)

            # 定义目标 URL 的路径部分
            target_url_pattern = "https://www.zhipin.com/wapi/zpjob/job/data/list"

            try:
                # 逐个处理 captured_urls 中的每个 URL
                for captured_url in captured_urls:
                    # 解析 URL
                    parsed_url = urlparse(captured_url)
                    url_path = f"{parsed_url.scheme}://{parsed_url.netloc}{parsed_url.path}"

                    # 检查 URL 路径是否匹配目标 URL
                    if url_path == target_url_pattern:
                        # print("是目标 URL 响应")
                        break
            except Exception as e:
                print(f"发生错误: {e}")

            # 使用检查 URL 是否包含目标路径部分
            if target_url_pattern not in urls:
                continue  # 如果匹配目标 URL，继续处理（或执行其他逻辑）

            # 打印请求的 URL
            print('请求 URL:', urls)
            # 获取请求的ID
            request_id = log['params']['requestId']
            # 获取响应头信息 (response headers)
            response_headers = log['params']['response'].get('headers', None)
            # 获取响应时间
            response_time = log['params']['response'].get('responseTime', None)
            # 获取响应状态码
            status_code = log['params']['response'].get('status', None)

            # 尝试获取请求的POST数据
            try:
                request_data = driver.execute_cdp_cmd('Network.getRequestPostData', {'requestId': request_id})
                print('请求数据:', request_data)
            except WebDriverException:  # 没有后台数据获取时会有异常
                request_data = None

            # 获取响应的主体内容
            try:
                response_body = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': request_id}).get(
                    'body', None)
                print('响应体:', response_body)
            except WebDriverException as e:
                print(f"获取响应失败: {e}")

            # 输出响应头 (response headers)，如果存在
            if response_headers:
                print('响应头:', response_headers)
            else:
                print('响应头未提供')

            # 输出响应状态码
            if status_code:
                print('响应状态码:', status_code)
            else:
                print('响应状态码未提供')

            # 输出响应时间
            if response_time:
                print('响应时间:', response_time)
            else:
                print('响应时间未提供')

    #         # 解析 JSON 数据
    #         data = json.loads(response_body)
    #         job_data = data.get('zpData', {}).get('data', [])
    #
    #         # 遍历数据并提取所需的字段
    #         for job in job_data:
    #             agent_id = '202501010001'
    #             job_id = job.get('encryptId', None)
    #             encrypt_job_id = job.get('encryptId', None)
    #             job_name = job.get('jobName', None)
    #             position_name = job.get('positionName', None)
    #             job_audit_status = job.get('jobAuditStatus', None)
    #             auth_token = "8486cf56-e9a6-4ea6-b877-af3334629159"
    #             job_status = job.get('jobStatus', None)
    #             show_type = job.get('showType', None)
    #             location_name = job.get('locationName', None)
    #             address_show_text = job.get('addressShowText', None)
    #             experience_name = job.get('experienceName', None)
    #             degree_name = job.get('degreeName', None)
    #             job_type_name = job.get('jobTypeName', None)
    #             paid_job_end_date = job.get('paidJobEndDate', None)
    #             brand_name = job.get('brandName', None)
    #             company_id = job.get('comId', None)
    #             low_salary = job.get('lowSalary', None)
    #             high_salary = job.get('highSalary', None)
    #             view_count = job.get('viewCount', None)
    #             concat_count = job.get('concatCount', None)
    #             interest_count = job.get('interestCount', None)
    #             add_time = job.get('addTime', None)
    #             update_time = job.get('updateTime', None)
    #             last_modify_time = job.get('lastModifyTime', None)
    #             salary_month = job.get('salaryMonth', None)
    #             free_experience = job.get('freeExperience', None)
    #             hot = job.get('hot', None)
    #             skill_require = job.get('skillRequire', None)
    #
    #             # 输出获取所有的字段值
    #             print(f"agent_id: {agent_id}")
    #             print(f"job_id: {job_id}")
    #             print(f"encryptId: {encrypt_job_id}")
    #             print(f"jobName: {job_name}")
    #             print(f"positionName: {position_name}")
    #             print(f"jobAuditStatus: {job_audit_status}")
    #             print(f"jobStatus: {job_status}")
    #             print(f"showType: {show_type}")
    #             print(f"locationName: {location_name}")
    #             print(f"addressShowText: {address_show_text}")
    #             print(f"experienceName: {experience_name}")
    #             print(f"degreeName: {degree_name}")
    #             print(f"jobTypeName: {job_type_name}")
    #             print(f"paidJobEndDate: {paid_job_end_date}")
    #             print(f"brandName: {brand_name}")
    #             print(f"companyId: {company_id}")
    #             print(f"lowSalary: {low_salary}")
    #             print(f"highSalary: {high_salary}")
    #             print(f"viewCount: {view_count}")
    #             print(f"concatCount: {concat_count}")
    #             print(f"interestCount: {interest_count}")
    #             print(f"addTime: {add_time}")
    #             print(f"updateTime: {update_time}")
    #             print(f"lastModifyTime: {last_modify_time}")
    #             print(f"salaryMonth: {salary_month}")
    #             print(f"freeExperience: {free_experience}")
    #             print(f"hot: {hot}")
    #             print(f"skillRequire: {skill_require}")
    #
    #             url = "http://192.168.0.132:7018/ai/job/add"
    #             headers = {"accept": "application/json, text/plain, */*"}
    #             data = {
    #                 "agent_id": agent_id,
    #                 "encrypt_job_id": encrypt_job_id,
    #                 "job_id": job_id,
    #                 "job_name": job_name,
    #                 "position_name": position_name,
    #                 "job_audit_status": job_audit_status,
    #                 "auth_token": auth_token,
    #                 "job_status": job_status,
    #                 "show_type": show_type,
    #                 "location_name": location_name,
    #                 "address_show_text": address_show_text,
    #                 "experience_name": experience_name,
    #                 "degree_name": degree_name,
    #                 "job_type_name": job_type_name,
    #                 "brand_name": brand_name,
    #                 "company_id": company_id,
    #                 "low_salary": low_salary,
    #                 "high_salary": high_salary,
    #                 "view_count": view_count,
    #                 "concat_count": concat_count,
    #                 "interest_count": interest_count,
    #                 "add_time": add_time,
    #                 "update_time": update_time,
    #                 "last_modify_time": last_modify_time,
    #                 "salary_month": salary_month,
    #                 "free_experience": free_experience,
    #                 "hot": hot,
    #                 "skill_require": skill_require,
    #                 "paid_job_end_date": paid_job_end_date
    #             }
    #             # "https://www.zhipin.com/wapi/zpjob/job/chatted/jobList"  # job_id字段上传接口
    #         # 发送 post 请求
    #         response = requests.post(url, headers=headers, data=data)
    #
    #         # 检查响应状态码
    #         if response.status_code == 200:
    #             # 成功响应，解析响应的 JSON 数据
    #             # response_data = response.json()
    #             print(response)
    #
    #     else:
    #         print(f"请求失败，错误信息: {response_data.get('message')}")
    # else:
    #     print(f"请求失败，状态码: {response.status_code}")



# def job():
#     print("执行定时任务: 每天10点发送请求")
#     get_boss_list(driver)
#
#
# def refresh():
#     # 启动时调用
#     get_boss_list(driver)
#
#     # 每天10点执行
#     schedule.every().day.at("10:00").do(job)
#
#     while True:
#         schedule.run_pending()
#         time.sleep(60)  # 每60秒检查一次
